%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 30.03.2009
%% Description: Iterator over all keys in an ets table.
%%--------------------------------------------------------------------
-module(iter_term_reader).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/2,
		 new_from_file/1,
		 new_from_console/1,
		 open/1,
		 next/1,
		 close/1,
		 test/0,
		 test/1
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------

new(DevFun,CloseFun) ->
	iter:from_module(?MODULE, {DevFun,CloseFun}).

new_from_file(Filename) ->
	new(fun() ->
				{ok,Dev}=file:open(Filename, [read]),
				{Dev,no_prompt}
		end,
		fun(Dev) ->
				file:close(Dev)
		end).

new_from_console(Prompt) ->
	new(fun() ->
				{standard_io,Prompt}
		end,
		fun(_Dev) ->
				ok
		end).

open({DevFun,CloseFun}) ->
	{Dev,Prompt}=DevFun(),
	{Dev,CloseFun,Prompt}.

next({Dev,_CloseFun,Prompt}=S) ->
	case io:read(Dev, Prompt) of
		eof ->
			{S,?EOF};
		{error,Info} ->
			exit({next_failed,Info});
		{ok,Term} ->
			{S,Term}
	end.

close({Dev,CloseFun,_Prompt}=_S) ->
	ok=CloseFun(Dev).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test() ->
	I=new_from_file("./triple.txt"),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.
test(con) ->
	I=new_from_console('term$ '),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------